package com.TeacherInfoServer.common.service.Impl;

import com.TeacherInfoServer.common.Result;
import com.TeacherInfoServer.pojo.entity.Department;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.pojo.entity.TypeInfo;
import com.TeacherInfoServer.common.service.DepartmentService;
import com.TeacherInfoServer.common.service.StatsService;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TypeInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StatsServiceImpl implements StatsService {
    @Resource
    private TeacherService teacherService;
    @Resource
    private TypeInfoService typeInfoService;
    @Resource
    private DepartmentService departmentService;

    @Override
    public Result<List<Map<String,Object>>> teacherStats(String typename) {
        List<TypeInfo> typeInfoList = typeInfoService.getOneNameList(typename);
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        String value = Teacher.IdFieldName.getValueByTypename(typename);
        wrapper.groupBy(value).select(value,"count(1) as amount");
        List<Map<String, Object>> mapList = teacherService.listMaps(wrapper);
        List<Map<String,Object>> statsMapList = mapList.stream()
                .peek(stringObjectMap -> typeInfoList.forEach(typeInfo -> {
                    if (stringObjectMap.get(value).equals(typeInfo.getId())) {
                        stringObjectMap.put("name",typeInfo.getValue());
                    }
                })).collect(Collectors.toList());
        return Result.success(statsMapList);
    }

    @Override
    public Result<List<Map<String,Object>>> departmentStats() {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.groupBy("department_id").select("department_id","count(1) as amount");
        List<Map<String, Object>> mapList = teacherService.listMaps(wrapper);
        List<Map<String,Object>> statsMapList = mapList.stream()
                .peek(stringObjectMap -> {
                     Department department = (departmentService.getById((Integer) stringObjectMap.get("department_id")));
                     stringObjectMap.put("name",department.getName());
                 }).collect(Collectors.toList());
        return Result.success(statsMapList);
    }

    @Override
    public Result<List<Map<String,Object>>> genderStats() {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.groupBy("gender").select("gender","count(1) as amount");
        List<Map<String, Object>> mapList = teacherService.listMaps(wrapper);
        return Result.success(mapList);
    }
}
